//
//  DealsRecordController.m
//  EMMApp
//
//  Created by 无常先生 on 2018/8/29.
//  Copyright © 2018年 YiXun. All rights reserved.
//

#import "DealsRecordController.h"
#import "SignDetailsViewController.h"
#import "SubscriptionDetailsViewController.h"
#import "FuzzySearchView.h"
#import "DealsRecordCell.h"
#import "DealsSubscribeApi.h"
#import "DealsSignApi.h"
#import "DealsSubscribeModel.h"
#import <MJExtension.h>

@interface DealsRecordController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listData;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, assign) BOOL flag;

@end

@implementation DealsRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavigationBar];
    [self prepareUI];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.flag = YES;
}
#pragma mark - setUpUI
- (void)setUpNavigationBar {
    [self updateNavBar];
    self.navigationItem.title =  self.typeFlag ? @"签约记录" : @"认购记录";
    [self configLeftBtn];
}

- (void)prepareUI {
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#f8f8f8"];
    
    UIView *topView = [[UIView alloc]init];
    topView.frame = CGRectMake(0, 0, self.view.frame.size.width, 50);
    topView.backgroundColor = [UIColor colorFromHexCode:@"#d9d9d9"];
    // 预防初始化时调用
    self.flag = NO;
    FuzzySearchView *searchView = [[FuzzySearchView alloc]initWithFrame:CGRectMake(15, 10, topView.frame.size.width - 30, 30) placeholderText:@"搜索" inputTextDidChange:^(NSString *text) {
        if (self.flag) {
            [self loadNewData:1 searchKey:text];
            self.tableView.mj_header.hidden = text.length;
            self.tableView.mj_footer.hidden = text.length;
        }
        
    } cancelClick:^{
        
    }];
    
    searchView.hiddenCancel = YES;
    [topView addSubview:searchView];
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.tableHeaderView = topView;
    tableView.tableFooterView = [UIView new];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    tableView.rowHeight = 100;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DealsRecordCell class]) bundle:nil] forCellReuseIdentifier:@"cellID"];
    [self.view addSubview:tableView];
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.index = 1;
        [self loadNewData:self.index searchKey:nil];
    }];
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadNewData:self.index++ searchKey:nil];
    }];
    self.tableView = tableView;
    [tableView.mj_header beginRefreshing];
    
}

#pragma mark - loadData
- (void)loadNewData:(NSInteger)idx searchKey:(NSString *)key {
    // 签约记录
    if (self.typeFlag) {
        DealsSignApi *api = [[DealsSignApi alloc]initWithQueryConditions:key pageNumber:idx];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            if (idx == 1) {
                [self.listData removeAllObjects];
            }
            NSDictionary *dict = request.responseJSONObject;
            DealsSubscribeModel *model = [DealsSubscribeModel mj_objectWithKeyValues:dict[@"resData"]];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.listData addObjectsFromArray:model.signedList];
            [self.tableView reloadData];
            if (idx != 1 && model.signedList.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            
        } failure:^(YTKBaseRequest *request) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }];
        
    }else {
        DealsSubscribeApi *api = [[DealsSubscribeApi alloc]initWithQueryConditions:key pageNumber:idx];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            if (idx == 1) {
                [self.listData removeAllObjects];
            }
            NSDictionary *dict = request.responseJSONObject;
            DealsSubscribeModel *model = [DealsSubscribeModel mj_objectWithKeyValues:dict[@"resData"]];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.listData addObjectsFromArray:model.subscribeList];
            [self.tableView reloadData];
             if (idx != 1 && model.subscribeList.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
        } failure:^(YTKBaseRequest *request) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }];
    }

}

#pragma mark - delegate & dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.statusLabel.hidden = self.listData.count > 0;
    return self.listData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DealsRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (self.typeFlag) {
        cell.signModel = self.listData[indexPath.row];
    }else {
        cell.subscribModel = self.listData[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DealsSubscriListModel *model = self.listData[indexPath.row];
    if(self.typeFlag) {
           // 签约详情
            SignDetailsViewController *kvc = [[SignDetailsViewController alloc] init];
            kvc.signedId = model.signedId;
//            kvc.getCustomerDetail = _getCustomerDetail;
//            kvc.customerId = _customerId;
            kvc.isNot = YES;
            [self.navigationController pushViewController:kvc animated:YES];
        
        
    }else {
        // 认购详情
            SubscriptionDetailsViewController  *kvc = [[SubscriptionDetailsViewController alloc] init];
            kvc.subscribeId = model.subscribeId;
            kvc.isNot = YES;
            [self.navigationController pushViewController:kvc animated:YES];
    }
    
}

#pragma mark - lazy
- (NSMutableArray *)listData {
    if (!_listData) {
        _listData = [NSMutableArray array];
    }
    return _listData;
}
- (UILabel *)statusLabel {
    if (!_statusLabel) {
        _statusLabel = [[UILabel alloc]init];
        _statusLabel.text = @"无符合条件的记录";
        _statusLabel.font = [UIFont systemFontOfSize:14];
        _statusLabel.textColor = [UIColor lightGrayColor];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        _statusLabel.frame = CGRectMake(0, self.tableView.frame.size.height * 0.2, self.tableView.frame.size.width, 30);
        _statusLabel.hidden = YES;
        [self.tableView addSubview:_statusLabel];
    }
    return _statusLabel;
    
}


@end
